//
//  TT_TabbarViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/4/1.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "TT_TabbarViewController.h"

@interface TT_TabbarViewController ()<UINavigationControllerDelegate,UITabBarControllerDelegate>

@property (nonatomic, assign) NSInteger indexFlag;

@end

@implementation TT_TabbarViewController

+ (instancetype)shareTabbar {
    
    static TT_TabbarViewController *shareTab = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!shareTab) {
            shareTab = [[self alloc] initWithContext:@""];
        }
    });
    return shareTab;
    
}

- (instancetype)initWithContext:(NSString *)context {
    /**
     * 以下两行代码目的在于手动设置让TabBarItem只显示图标，不显示文字，并让图标垂直居中。
     * 等 效于在 `-tabBarItemsAttributesForController` 方法中不传 `CYLTabBarItemTitle` 字段。
     * 更推荐后一种做法。
     */
    UIEdgeInsets imageInsets = UIEdgeInsetsZero;//UIEdgeInsetsMake(4.5, 0, -4.5, 0);
    UIOffset titlePositionAdjustment = UIOffsetMake(0, -3.5);
    if (self = [super initWithViewControllers:[self viewControllersForTabBar]
                        tabBarItemsAttributes:[self tabBarItemsAttributesForTabBar]
                                  imageInsets:imageInsets
                      titlePositionAdjustment:titlePositionAdjustment
                                      context:context
                ]) {
        [self customizeTabBarAppearanceWithTitlePositionAdjustment:titlePositionAdjustment];
        self.delegate = self;
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBar.translucent = NO;
    
    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    [self becomeFirstResponder];
}

- (void)setCurrentIndex:(TT_TabbarIndexType)indexType {
    
    [[TT_TabbarViewController shareTabbar] setSelectedIndex:indexType];
}

- (TT_NavigationViewController *)configVCWithClassName:(NSString *)className {
    Class cls = NSClassFromString(className);
    UIViewController *viewController = [[cls alloc] init];
    TT_NavigationViewController *navController = [[TT_NavigationViewController alloc]
                                                   initWithRootViewController:viewController];
    navController.navigationBar.translucent = NO;
    navController.navigationBar.barTintColor = [UIColor whiteColor];
    [viewController cyl_setHideNavigationBarSeparator:YES];
    return navController;
}

- (NSArray *)viewControllersForTabBar {
    _homeNav = [self configVCWithClassName:@"HomeFlowViewController"];
    //_categoryNav = [self configVCWithClassName:@"CategoryViewController"];
    _communityNav = [self configVCWithClassName:@"TanHunLunJiaViewController"];
    _baikeNav = [self configVCWithClassName:@"BaiKeMainViewController"];
    _mineNav = [self configVCWithClassName:@"MineVc"];
    return @[_homeNav, _communityNav, _baikeNav, _mineNav];
}

- (NSArray *)tabBarItemsAttributesForTabBar {
    // lottie动画的json文件来自于NorthSea, respect!
    NSDictionary *homeTabbar = @{CYLTabBarItemTitle : @"首页",
                                 CYLTabBarItemImage : @"home_nor",
                                 CYLTabBarItemSelectedImage : @"home_sel"};
    
    //NSDictionary *catTabbar = @{CYLTabBarItemTitle : @"婚品",
                                //CYLTabBarItemImage : @"pro_nor",
                                //CYLTabBarItemSelectedImage : @"pro_sel"};
    
    NSDictionary *communityTabbar = @{CYLTabBarItemTitle : @"TA说",
                                      CYLTabBarItemImage : @"tashuo_nor",
                                      CYLTabBarItemSelectedImage : @"tashuo_sel"};
    
    NSDictionary *baikeTabbar = @{CYLTabBarItemTitle : @"百科",
                                  CYLTabBarItemImage :@"baike_nor",
                                  CYLTabBarItemSelectedImage : @"baike_sel"};
    
    NSDictionary *mineTabbar = @{CYLTabBarItemTitle : @"我的",
                                 CYLTabBarItemImage :@"mine_nor",
                                 CYLTabBarItemSelectedImage : @"mine_sel"};
    
    return @[homeTabbar,communityTabbar,baikeTabbar,mineTabbar];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSInteger index = [tabBar.items indexOfObject:item];
    if (index == 9999) {
    //if (index == TT_TabbarIndexType_Community) {
        
        [Utilities tapticEngineWork];
        NSMutableArray <UIView *>*array = @[].mutableCopy;
        for (UIView *btn in tabBar.subviews) {
            if ([btn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
                [array addObject:btn];
            }
        }
        
        CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        ani.duration = 0.2;
        ani.repeatCount = 1;
        ani.autoreverses = YES;
        ani.fromValue = [NSNumber numberWithFloat:0.95];
        ani.toValue = [NSNumber numberWithFloat:1.2];
        [[array[index] layer] addAnimation:ani forKey:nil];
    }
}


/**
 *  更多TabBar自定义设置：比如：tabBarItem 的选中和不选中文字和背景图片属性、tabbar 背景图片属性等等
 */
- (void)customizeTabBarAppearanceWithTitlePositionAdjustment:(UIOffset)titlePositionAdjustment {

    [self rootWindow].backgroundColor = UIColor.whiteColor;
    
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = UIColorHex(0x898991);
    
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = UIColorHex(0xFE760F);
    

    if (@available(iOS 13.0, *)) {
        UITabBarItemAppearance *inlineLayoutAppearance = [[UITabBarItemAppearance  alloc] init];
        inlineLayoutAppearance.normal.titlePositionAdjustment = titlePositionAdjustment;

        // set the text Attributes
        // 设置文字属性
        [inlineLayoutAppearance.normal setTitleTextAttributes:normalAttrs];
        [inlineLayoutAppearance.selected setTitleTextAttributes:selectedAttrs];

        UITabBarAppearance *standardAppearance = [[UITabBarAppearance alloc] init];
        standardAppearance.stackedLayoutAppearance = inlineLayoutAppearance;
        standardAppearance.backgroundColor = UIColor.whiteColor;
        //shadowColor和shadowImage均可以自定义颜色, shadowColor默认高度为1, shadowImage可以自定义高度.
        standardAppearance.shadowColor = UIColor.whiteColor;
        // standardAppearance.shadowImage = [[self class] imageWithColor:[UIColor cyl_systemGreenColor] size:CGSizeMake([UIScreen mainScreen].bounds.size.width, 1)];
        self.tabBar.standardAppearance = standardAppearance;
        
    } else {
        // Override point for customization after application launch.
        // set the text Attributes
        // 设置文字属性
        UITabBarItem *tabBar = [UITabBarItem appearance];
        [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
        [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
        
        [[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];
        [[UITabBar appearance] setShadowImage:[Utilities imageWithColor:UIColor.whiteColor]];
    }
}

@end
